// firstPackage/pages/liveModule/applyLiveRoom/applyLiveRoom.js
import { chooseAndUploadQiniuActicon } from "../../../../service/upload_service"
import { createLiveApply } from "../../../../service/user_service"
import debounce from "../../../../tools/debounce"
import { URL, NEWIMAGE_URL } from "../../../../service/base_service"

let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    themeStyle: "",
    showSuccessPop: false,
    openId: "",
    formData: {
      name: "",
      startTimeStr: "",
      endTimeStr: "",
      createNickName: "",
      createrWechat: "",
      anchorName: "",
      anchorWechat: "",
      closeComment: 0,//1:关闭
      closeLike: 0,//1:关闭
      closeReplay: 0,//1:关闭
      houseNumber: "",
      houseName: "",
      shareImg: "",//分享图
      coverImg: "",//封面图
      coverLocalImg: "",
      // backImg: "",//背景墙
      feedsImg: "",

    },
    tempShareImgPath: "",
    tempCoverImgPath: "",
    showLiveTimePop: false,
    maxDate: new Date(2025, 12, 31).getTime(),
    minDate: new Date(2021, 11, 7).getTime(),
    currentTimeType: 1,//1:开始时间，2:结束时间
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      openId: wx.getStorageSync('openId')
    })
  },



  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.themeStyle) {
      this.setData({
        themeStyle: app.globalData.themeStyle
      })
    }
    if (JSON.stringify(app.globalData.articleHouse) != "{}") {
      console.log("JJLog:返回的是啥:" + JSON.stringify(app.globalData.articleHouse));
      this.setData({
        'formData.houseName': app.globalData.articleHouse.name,
        'formData.houseNumber': app.globalData.articleHouse.houseNumber
      })
      app.globalData.articleHouse = {}
    }
  },

  //选择开播时间
  showSelectPopup(e) {
    let index = e.currentTarget.dataset.seindex;
    if (index == 1) {
      this.setData({
        showLiveTimePop: true,
        currentTimeType: 1,
      })
    } else if (index == 2) {
      this.setData({
        showLiveTimePop: true,
        currentTimeType: 2,
      })
    } else if (index == 3) {
      wx.navigateTo({
        url: '/formPackage/pages/article/selectArticleHouse/selectArticleHouse',
      })
    }
  },

  timePopHidden() {
    this.setData({
      showLiveTimePop: false,
    })
  },
  //时间确认选择
  deliveryTimeSure(e) {
    console.log("JJLog:时间是:" + JSON.stringify(e));
    if (this.data.currentTimeType == 1) {
      this.setData({
        'formData.startTimeStr': e.detail.timeStr
      })
    } else {
      this.setData({
        'formData.endTimeStr': e.detail.timeStr
      })
    }
    this.timePopHidden();
  },
  //上传单张图片:
  pushImgAction(e) {
    let type = e.currentTarget.dataset.type;
    let url = URL + "/live/get/media/id"
    let that = this;
    let tempFilePaths = [];
    wx.chooseImage({
      count: 1, //最多可以选择的图片总数
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有   
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        wx.showLoading({
          title: '上传中请等待',
          icon: "none"
        })
        tempFilePaths = res.tempFilePaths;
        //启动上传等待中...
        console.log("JJLog:选中是:" + JSON.stringify(tempFilePaths));
        that.secondUploadImg(tempFilePaths[0]);
        wx.uploadFile({
          url: url,
          filePath: tempFilePaths[0],
          name: 'image',
          header: {
            "Content-Type": "multipart/form-data",
            'Authorization': that.data.openId
          },
          formData: {
            type: "share",
          },
          success: function (res) {
            wx.hideLoading()
            console.log("JJLog:上传图片成功:" + JSON.stringify(res));
            if (res.statusCode == 200) {
              let resultData = JSON.parse(res.data);
              if (resultData.code == 200) {
                let mediaID = resultData.data;
                if (type == "share") {
                  that.setData({
                    'formData.shareImg': mediaID,
                    tempShareImgPath: tempFilePaths[0]
                  })
                } else if (type == "cover") {
                  that.setData({
                    'formData.coverImg': mediaID,
                    tempCoverImgPath: tempFilePaths[0]
                  })
                }
              }
            }

          },
          fail: function (res) {
            wx.hideLoading()
            wx.showToast({
              title: '上传图片失败',
              icon: "none"
            })
          }
        });
      },
      fail: err => {
        wx.showToast({
          title: '选择图片失败',
          icon: "none"
        })
      }
    })





    // chooseAndUploadQiniuActicon('cover').then(res => {
    //   console.log("JJLog:图片上传成功:" + JSON.stringify(res));
    //   wx.showToast({
    //     title: '上传成功',
    //   })
    //   this.setData({
    //     'formData.coverLocalImg': res.complateUrl
    //   })



    // }).catch(err => {
    //   console.log("JJLog:图片上传失败:" + JSON.stringify(err));
    //   // wx.showToast({
    //   //   title: '图片上传失败',
    //   //   icon: "none"
    //   // })
    // })

  },
  secondUploadImg(filePath) {
    let that = this;
    let qiuUrl = "https://up-z2.qiniup.com"
    let expandName = filePath.substring(filePath.length - 10, filePath.length)
    wx.uploadFile({
      url: qiuUrl,
      filePath: filePath,
      name: 'file',
      formData: {
        'token': wx.getStorageSync('qiniu_token'),
        'key': "cover" + "/" + new Date().getTime() + expandName,
      },
      header: {
        "Content-Type": "multipart/form-data"
      },
      success: function (res) {
        let resultData = JSON.parse(res.data);
        let coverImg = NEWIMAGE_URL + resultData.key
        that.setData({
          'formData.coverLocalImg': coverImg
        })
      },
      fail: function (res) {

      }
    });

  },

  //开关切换
  upOrDownClick(e) {
    let type = e.currentTarget.dataset.type;
    if (type == "like") {
      let closeLike = this.data.formData.closeLike;
      this.setData({
        'formData.closeLike': closeLike == 0 ? 1 : 0
      })
    } else if (type == "comment") {
      this.setData({
        'formData.closeComment': this.data.formData.closeComment == 0 ? 1 : 0
      })
    } else if (type == "reply") {
      this.setData({
        'formData.closeReplay': this.data.formData.closeReplay == 0 ? 1 : 0
      })
    }
  },
  //输入绑定
  bindInputValue(e) {
    let key = e.currentTarget.dataset.key;
    let ckey = `formData.${key}`
    this.setData({
      [ckey]: e.detail.value
    })
  },

  //提交按钮点击:
  submitApplyAction() {
    let data = this.data.formData;
    if (!data.name) {
      wx.showToast({
        title: '未填写标题',
        icon: "none"
      })
      return;
    }
    if (!data.shareImg) {
      wx.showToast({
        title: '请上传分享封面图',
        icon: "none"
      })
      return;
    }
    if (!data.coverImg) {
      this.setData({
        'formData.coverImg': data.shareImg
      })
    }
    if (!data.feedsImg) {
      this.setData({
        'formData.feedsImg': data.shareImg
      })
    }
    if (!data.startTimeStr) {
      wx.showToast({
        title: '请选择直播开始时间',
        icon: "none"
      })
      return;
    }
    if (!data.endTimeStr) {
      wx.showToast({
        title: '请选择直播结束时间',
        icon: "none"
      })
      return;
    }
    if (!data.anchorName) {
      wx.showToast({
        title: '请输入主播昵称',
        icon: "none"
      })
    }
    if (!data.anchorWechat) {
      wx.showToast({
        title: '请输入主播微信号',
        icon: "none"
      })
    }

    console.log("JJLog:直播申请参数:" + JSON.stringify(this.data.formData));
    debounce(this.createLiveApply);
  },

  //创建申请请求:
  createLiveApply() {
    wx.showLoading();
    createLiveApply(this.data.formData).then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        this.setData({
          showSuccessPop: true
        })
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "创建失败",
        icon: "none",
        duration: 3500
      })
      console.error("JJLog:createLiveApply", err);
    })
  },
  successPopSure() {
    this.setData({
      showSuccessPop: false
    })
    wx.navigateBack({
      delta: 0,
    })
  },

})